package com.example.myhl7project;

import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.parser.PipeParser;
import ca.uhn.hl7v2.util.Terser;
import ca.uhn.hl7v2.validation.impl.ValidationContextFactory;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class HL7Processor implements Processor {
    private static final Logger logger = LoggerFactory.getLogger(HL7Processor.class);
    private final PipeParser parser;

    public HL7Processor() {
        // 关闭 HL7 校验器（兼容设备厂商自定义字段）
        parser = new PipeParser();
        parser.setValidationContext(ValidationContextFactory.noValidation());
    }

    @Override
    public void process(Exchange exchange) throws Exception {
        // 原始 HL7 文本（包含 MLLP \x0b...\x1c\r 的情况由 Camel MLLP 自动剥离）
        String hl7Raw = exchange.getIn().getBody(String.class);

        if (!isValidHL7Structure(hl7Raw)) {
            logger.warn("⚠️ 收到非法 HL7 消息:\n{}", hl7Raw);
            return;
        }

        // 解析 HL7
        Message message = parser.parse(hl7Raw);
        Terser terser = new Terser(message);

        String messageType = terser.get("/MSH-9-1");
        String triggerEvent = terser.get("/MSH-9-2");
        String controlId = terser.get("/MSH-10");
        String charset = terser.get("/MSH-18");

        logger.info("🔍 HL7 类型: {}^{} | 控制ID: {} | 字符集: {}", messageType, triggerEvent, controlId, charset);

        // 设置 exchange 属性
        exchange.setProperty("HL7_CHARSET", charset != null ? charset : "ISO-8859-1");
        exchange.setProperty("MSH_10_CONTROL_ID", controlId);
        exchange.setProperty("ORIGINAL_MESSAGE", message.encode());
    }

    private boolean isValidHL7Structure(String hl7) {
        return hl7 != null &&
                hl7.startsWith("MSH|") &&
                hl7.contains("\rPID|") &&
                hl7.contains("\rOBX|");
    }

    private String sanitizePHI(String hl7) {
        // PID-5 (患者姓名) 脱敏
        hl7 = hl7.replaceAll("(PID\\|[^\\r]*\\|[^\\r]*\\|[^\\r]*\\|)[^\\|]+(\\|)", "$1***$2");
        // PID-3 (患者ID) 脱敏
        hl7 = hl7.replaceAll("(PID\\|[^\\r]*\\|)[^\\|]+(\\|)", "$1***$2");
        return hl7;
    }

    private String extractCharset(String hl7) {
        String[] segments = hl7.split("\r");
        for (String segment : segments) {
            if (segment.startsWith("MSH")) {
                String[] fields = segment.split("\\|");
                if (fields.length > 18 && !fields[18].isEmpty()) {
                    return fields[18];
                }
            }
        }
        return null;
    }

    private String extractControlId(String hl7) {
        String[] segments = hl7.split("\r");
        for (String segment : segments) {
            if (segment.startsWith("MSH")) {
                String[] fields = segment.split("\\|");
                if (fields.length > 9 && !fields[9].isEmpty()) {
                    return fields[9];
                }
            }
        }
        return "";
    }
}
